package com.toocms.jinjuhang.ui.advert_list

import android.app.Application
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableField
import com.toocms.jinjuhang.R
import com.toocms.jinjuhang.BR
import com.toocms.jinjuhang.config.Urls
import com.toocms.jinjuhang.config.UserRepository
import com.toocms.jinjuhang.data.center.VideoListData
import com.toocms.jinjuhang.widget.view_model.requestData
import com.toocms.tab.base.BaseModel
import com.toocms.tab.base.BaseViewModel
import com.toocms.tab.binding.ItemBinding
import com.toocms.tab.binding.command.BindingAction
import com.toocms.tab.binding.command.BindingCommand
import com.toocms.tab.bus.event.SingleLiveEvent

class AdvertListModel(application: Application) : BaseViewModel<BaseModel>(application) {
    var p = 1
    var keywords = ""

    val keywordsObservableField = ObservableField<String>()

    val items = ObservableArrayList<AdvertListItemModel>()
    val itemBinding =
        ItemBinding.of<AdvertListItemModel>(BR.advertListItemModel, R.layout.item_advert_list)

    val stopRefreshOrLoadSingleLiveEvent = SingleLiveEvent<Unit>()
    val backClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        finishFragment()
    })
    val refreshBindingCommand = BindingCommand<BindingAction>(BindingAction {
        refresh()
    })
    val loadBindingCommand = BindingCommand<BindingAction>(BindingAction {
        load()
    })

    val searchClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        keywords = keywordsObservableField.get() ?: ""
        refresh()
    })


    init {
        refresh(true)
    }

    private fun refresh(isShowLoading: Boolean = false) {
        p = 1
        videoList(p, isShowLoading)
    }

    private fun load() {
        p++
        videoList(p)

    }


    private fun videoList(p: Int, isShowLoading: Boolean = false) {
        val params = mutableMapOf<String, String?>()
        params["member_id"] = UserRepository.user.member_id
        params["keywords"] = keywords
        params["p"] = p.toString()
        requestData(
            Urls.Center.VIDEO_LIST,
            params,
            resultClass = VideoListData::class.java,
            isShowLoading = isShowLoading,
            result = {
                if (1 == p) items.clear()
                it.list?.forEach { item ->
                    items += AdvertListItemModel(this, ObservableField(item))
                }
            },
            finish = {
                stopRefreshOrLoadSingleLiveEvent.call()
            })
    }


}